import { View, Image } from '@tarojs/components';
import { AtInputNumber, AtButton } from 'taro-ui';
import { useState } from 'react';
import Modal from '../Modal';
import Price from '../Price';
import Select from '../Select';
import './index.scss';

interface ISkuItem {
  pid: number;
  skuName: string;
  skuId: string | number;
}

export default function ({ show, skuInfo, skuList, onChangeSku, onCountChange, onSubmit }) {
  const [choosed, setChoosed] = useState<ISkuItem[]>([]);
  const [disabled, setDisabled] = useState<boolean>(true);
  const onChange = ({ pid, skuId }) => {
    let tempChoosed = choosed;
    const skuName = skuList
      .filter((item) => item.id === pid)?.[0]
      ?.skus.filter((item) => item.id === skuId)?.[0].name;
    const hasIndex = tempChoosed.findIndex((item) => item.pid === pid);
    if (hasIndex > -1) {
      tempChoosed[hasIndex].skuId = skuId;
      tempChoosed[hasIndex].skuName = skuName;
    } else {
      tempChoosed.push({
        pid: pid,
        skuId: skuId,
        skuName: skuName,
      });
    }
    setChoosed(tempChoosed);
    setDisabled(tempChoosed.length < skuList.length);
    onChangeSku(tempChoosed);
  };
  const _onCountChange = (count: number) => {
    onCountChange?.(count);
  };

  return (
    <Modal title="选择规格" show={show} className="sku-modal-container">
      <View className="sku-info">
        <View className="sku-image">
          <Image src={skuInfo.imageUrl} />
        </View>
        <View className="sku-title">
          <View className="sku-name">{skuInfo.goodsName}</View>
          <View className="price-text">
            <Price price={skuInfo.price} />
          </View>
        </View>
      </View>
      <View className="choose-sku-title">选择规格</View>
      {console.log('choosed', choosed.length)}
      <View className="sku-list">
        {skuList.map((item) => {
          return (
            <View className="sku-item" key={item.id}>
              <View className="sku-item__left">{item.name}</View>
              <View className="sku-item__right">
                <Select
                  list={item.skus.map((sku) => ({ ...sku, value: sku.id }))}
                  active={choosed.filter((choose) => choose.pid === item.id)?.[0]?.skuId}
                  onChange={(value: string | number) =>
                    onChange({
                      pid: item.id,
                      skuId: value,
                    })
                  }
                />
              </View>
            </View>
          );
        })}
      </View>
      <View className="choose-sku-title goods-count">
        购买数量
        {show && <AtInputNumber
          type="digit"
          min={1}
          width={40}
          step={1}
          value={skuInfo.count}
          onChange={_onCountChange}
        />}
      </View>
      <View className="bottom-btn">
        <AtButton type="primary" disabled={disabled} onClick={onSubmit}>
          确定
        </AtButton>
      </View>
    </Modal>
  );
}
